# coding: utf-8
from typing import List

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout

from .content_widget import ContentWidget
from ...common import HomeItemModel, signalBus, APIBase, cfg
from ...components import queue_thread_manager, VerticalScrollArea


class HomeInterface(VerticalScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.view)
        self.items = []

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName('HomeInterface')
        self.setWidget(self.view)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        signalBus.homeChangedSignal.connect(self.loadHome)

    def loadHome(self, plugin: APIBase):
        cfg.set(cfg.homePlugin, plugin.name)
        queue_thread_manager.send_function(plugin.home, slot=self.updateHomeResult)

    def updateHomeResult(self, home_items: List[HomeItemModel]):
        self.clear()
        for item in home_items:
            content_widget = ContentWidget(self)
            content_widget.setModel(item)
            self.items.append(content_widget)
            self.verticalLayout.addWidget(content_widget)

    def clear(self):
        for item in self.items:
            self.verticalLayout.removeWidget(item)
            item.deleteLater()
        self.items.clear()
